package com.wangan.wanganpush.utils;

import com.wangan.wanganpush.props.MyProps;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 将string字符串转化为xml文件
 */
@Service
public class StringToXml {
    @Resource
    MyProps myProps;

    public  String  stringToXml(String xmlStr,String fileName){
        String filePath = myProps.getJarPath() ;
        if(xmlStr == null || "".equals(xmlStr.trim())) return null;
        try {
            SAXReader saxReader = new SAXReader();
            Document document;
            try {
                document= saxReader.read(new ByteArrayInputStream(xmlStr.getBytes("utf-8")));
                OutputFormat format = OutputFormat.createPrettyPrint();

                //判断文件目录是否存在
                File file = new File(filePath+fileName+"/"+fileName+".xml");
                if(!file.getParentFile().exists()){
                    file.getParentFile().mkdirs();
                }

                /** 将document中的内容写入文件中 */
                XMLWriter writer = new XMLWriter(new FileWriter(file),format);
                writer.write(document);
                writer.close();

                System.out.println(filePath+fileName);
                Boolean flag=fileToZip(filePath+fileName,filePath,fileName);

                //打成zip包后删除原文件夹
                deleteSourceFile(filePath+fileName);

                if(flag){
                    System.out.println(filePath+fileName+".zip");
                   return  fileName+".zip";
                }
                /*ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(filePath+fileName+".zip"));
                ZipEntry entry = new ZipEntry(filePath+fileName+"\\"+fileName);
                zipOut.putNextEntry(entry);
                DataOutputStream dataOs = new DataOutputStream(zipOut);
                dataOs.write(xmlStr.toString().getBytes("utf-8"));
                dataOs.close();*/
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将文件夹整个打包成为zip文件
     * @return
     */
    private boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName){
        boolean flag = false;
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;

        if(sourceFile.exists() == false){
            System.out.println("待压缩的文件目录："+sourceFilePath+"不存在.");
        }else{
            try {
                File zipFile = new File(zipFilePath + "/" + fileName +".zip");
                if(zipFile.exists()){
                    System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");
                }else{
                    File[] sourceFiles = sourceFile.listFiles();
                    if(null == sourceFiles || sourceFiles.length<1){
                        System.out.println("待压缩的文件目录：" + sourceFilePath + "里面不存在文件，无需压缩.");
                    }else{
                        fos = new FileOutputStream(zipFile);
                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
                        byte[] bufs = new byte[1024*10];
                        for(int i=0;i<sourceFiles.length;i++){
                            //创建ZIP实体，并添加进压缩包
                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                            zos.putNextEntry(zipEntry);
                            //读取待压缩的文件并写进压缩包里
                            fis = new FileInputStream(sourceFiles[i]);
                            bis = new BufferedInputStream(fis, 1024*10);
                            int read = 0;
                            while((read=bis.read(bufs, 0, 1024*10)) != -1){
                                zos.write(bufs,0,read);
                            }
                        }
                        flag = true;
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally{
                //关闭流
                try {
                    if(null != bis) bis.close();
                    if(null != zos) zos.close();
                    if(null != fis) fis.close();
                    if(null != fos) fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return flag;
    }

   //打成zip包之后删除原文件夹
    private Boolean deleteSourceFile(String dirPath){
        try {
            File file = new File(dirPath);
            if(file.isFile())
            {
                file.delete();
            }else
            {
                File[] files = file.listFiles();
                if(files == null)
                {
                    file.delete();
                }else
                {
                    for (int i = 0; i < files.length; i++)
                    {
                        deleteSourceFile(files[i].getAbsolutePath());
                    }
                    file.delete();
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

       return true;
    }

}
